package com.szgz.platform.controller;

import com.szgz.platform.model.User;
import com.szgz.platform.model.UserEnvironment;
import com.szgz.platform.model.UserResource;
import com.szgz.platform.service.UserManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szgz.platform.result.ApiResponse;
import com.szgz.platform.result.PageResult;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 用户管理控制器
 * 提供用户环境管理的REST API接口
 */
@RestController
@RequestMapping("/api/users")
@CrossOrigin(origins = "*")
public class UserManagementController {
    
    @Autowired
    private UserManagementService userManagementService;
    
    /**
     * 创建新用户
     */
    @PostMapping
    public ResponseEntity<ApiResponse<User>> createUser(@RequestBody User user) {
        try {
            User createdUser = userManagementService.createUser(user);
            return ResponseEntity.ok(ApiResponse.success(createdUser));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }
    
    /**
     * 获取所有用户列表
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<User>>> getAllUsers() {
        List<User> users = userManagementService.getAllUsers();
        return ResponseEntity.ok(ApiResponse.success(users));
    }
    
    /**
     * 根据ID获取用户
     */
    @GetMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> getUserById(@PathVariable String userId) {
        return userManagementService.findUserById(userId)
                .map(u -> ResponseEntity.ok(ApiResponse.success(u)))
                .orElse(ResponseEntity.status(404).body(ApiResponse.fail(404, "User not found")));
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/{userId}")
    public ResponseEntity<ApiResponse<User>> updateUser(@PathVariable String userId, @RequestBody User user) {
        try {
            user.setUserId(userId);
            User updatedUser = userManagementService.updateUser(user);
            return ResponseEntity.ok(ApiResponse.success(updatedUser));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public ResponseEntity<ApiResponse<Void>> deleteUser(@PathVariable String userId) {
        boolean deleted = userManagementService.deleteUser(userId);
        return deleted ? ResponseEntity.ok(ApiResponse.success()) : ResponseEntity.status(404).body(ApiResponse.fail(404, "User not found"));
    }
    
    /**
     * 创建用户环境
     */
    @PostMapping("/{userId}/environment")
    public ResponseEntity<ApiResponse<UserEnvironment>> createUserEnvironment(
            @PathVariable String userId,
            @RequestParam String userRole,
            @RequestParam String environmentTypes,
            @RequestParam(required = false) String operatorRole) {
        try {
            // 校验操作人角色：仅 ADMIN/TEACHER 允许创建环境
            String roleForCheck = operatorRole != null ? operatorRole : userRole;
            if (!isOperatorAllowed(roleForCheck)) {
                throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can create environment");
            }
            Set<UserEnvironment.EnvironmentType> envTypes = parseEnvironmentTypes(environmentTypes);
            UserEnvironment environment = userManagementService.createUserEnvironment(userId, userRole, envTypes);
            return ResponseEntity.ok(ApiResponse.success(environment));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }
    
    /**
     * 创建指定类型的用户环境
     */
    @PostMapping("/{userId}/environment/selective")
    public ResponseEntity<ApiResponse<UserEnvironment>> createSelectiveUserEnvironment(
            @PathVariable String userId,
            @RequestParam String userRole,
            @RequestParam String environmentTypes,
            @RequestParam(required = false) String operatorRole) {
        try {
            // 校验操作人角色：仅 ADMIN/TEACHER 允许创建环境
            String roleForCheck = operatorRole != null ? operatorRole : userRole;
            if (!isOperatorAllowed(roleForCheck)) {
                throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can create environment");
            }
            Set<UserEnvironment.EnvironmentType> envTypes = parseEnvironmentTypes(environmentTypes);
            UserEnvironment environment = userManagementService.createUserEnvironment(userId, userRole, envTypes);
            return ResponseEntity.ok(ApiResponse.success(environment));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    private boolean isOperatorAllowed(String role) {
        if (role == null) return false;
        String r = role.trim().toLowerCase();
        return "admin".equals(r) || "teacher".equals(r);
    }

    /**
     * 创建共享 IDE 环境（单容器多进程，多用户目录隔离）
     * 请求体示例：
     * {"groupId":"class001", "studentIds":["stu01","stu02"], "operatorRole":"admin"}
     */
    @PostMapping("/shared/environment/ide")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createSharedIdeEnvironment(@RequestBody Map<String, Object> body) {
        String operatorRole = (String) body.getOrDefault("operatorRole", "");
        if (!isOperatorAllowed(operatorRole)) {
            throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can create shared environment");
        }

        String groupId = (String) body.get("groupId");
        Object ids = body.get("studentIds");
        if (groupId == null || ids == null) {
            return ResponseEntity.badRequest().body(ApiResponse.fail("groupId and studentIds are required"));
        }

        java.util.List<String> studentIds;
        if (ids instanceof java.util.List) {
            studentIds = ((java.util.List<?>) ids).stream().map(Object::toString).collect(java.util.stream.Collectors.toList());
        } else if (ids instanceof String) {
            studentIds = java.util.Arrays.stream(((String) ids).split(",")).map(String::trim).filter(s -> !s.isEmpty()).collect(java.util.stream.Collectors.toList());
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.fail("studentIds must be array or comma-separated string"));
        }

        try {
            Map<String, Object> result = userManagementService.createSharedIDEEnvironment(groupId, studentIds);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /**
     * 删除共享 IDE 环境
     */
    @DeleteMapping("/shared/environment/ide")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteSharedIdeEnvironment(@RequestParam String groupId,
                                                                          @RequestParam(required = false) String operatorRole) {
        if (!isOperatorAllowed(operatorRole)) {
            throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can delete shared environment");
        }
        try {
            Map<String, Object> result = userManagementService.deleteSharedIDEEnvironment(groupId);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /**
     * 生成 Nginx 反向代理配置（将多端口收敛为单域名路径）
     */
    @GetMapping(value = "/shared/environment/ide/nginx", produces = "text/plain;charset=UTF-8")
    @com.szgz.platform.config.SkipWrap
    public ResponseEntity<String> generateSharedIdeNginx(@RequestParam String groupId,
                                                         @RequestParam String serverName,
                                                         @RequestParam(required = false, defaultValue = "/") String basePath,
                                                         @RequestParam(required = false) String operatorRole) {
        if (!isOperatorAllowed(operatorRole)) {
            return ResponseEntity.status(403).body("Forbidden: only admin/teacher can generate nginx config");
        }
        try {
            String conf = userManagementService.generateSharedIDENginxConfig(groupId, serverName, basePath);
            return ResponseEntity.ok(conf);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }
    
    /**
     * 启动用户环境
     */
    @PostMapping("/{userId}/environment/start")
    public ResponseEntity<ApiResponse<Map<String, Object>>> startUserEnvironment(@PathVariable String userId) {
        boolean started = userManagementService.startUserEnvironment(userId);
        Map<String, Object> response = Map.of(
            "started", started,
            "message", started ? "Environment started successfully" : "Failed to start environment"
        );
        return ResponseEntity.ok(started ? ApiResponse.success(response) : ApiResponse.fail("Failed to start environment"));
    }
    
    /**
     * 停止用户环境
     */
    @PostMapping("/{userId}/environment/stop")
    public ResponseEntity<ApiResponse<Map<String, Object>>> stopUserEnvironment(@PathVariable String userId) {
        boolean stopped = userManagementService.stopUserEnvironment(userId);
        Map<String, Object> response = Map.of(
            "stopped", stopped,
            "message", stopped ? "Environment stopped successfully" : "Failed to stop environment"
        );
        return ResponseEntity.ok(stopped ? ApiResponse.success(response) : ApiResponse.fail("Failed to stop environment"));
    }
    
    /**
     * 删除用户环境
     */
    @DeleteMapping("/{userId}/environment")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteUserEnvironment(@PathVariable String userId,
                                                                     @RequestParam(required = false) String operatorRole) {
        // 仅 ADMIN/TEACHER 可删除环境
        if (!isOperatorAllowed(operatorRole)) {
            return ResponseEntity.status(403).body(ApiResponse.fail(403, "Forbidden: only admin/teacher can delete environment"));
        }
        boolean deleted = userManagementService.deleteUserEnvironment(userId);
        Map<String, Object> response = Map.of(
            "deleted", deleted,
            "message", deleted ? "Environment deleted successfully" : "Failed to delete environment"
        );
        return ResponseEntity.ok(deleted ? ApiResponse.success(response) : ApiResponse.fail("Failed to delete environment"));
    }
    
    /**
     * 获取用户环境状态
     */
    @GetMapping("/{userId}/environment")
    public ResponseEntity<ApiResponse<UserEnvironment>> getUserEnvironmentStatus(@PathVariable String userId) {
        UserEnvironment environment = userManagementService.getUserEnvironmentStatus(userId);
        return environment != null ? ResponseEntity.ok(ApiResponse.success(environment)) : ResponseEntity.status(404).body(ApiResponse.fail(404, "Not Found"));
    }
    
    /**
     * 获取用户环境访问信息
     */
    @GetMapping("/{userId}/environment/access")
    public ResponseEntity<ApiResponse<UserEnvironment>> getAccessInfo(@PathVariable String userId) {
        UserEnvironment environment = userManagementService.getAccessInfo(userId);
        return environment != null ? ResponseEntity.ok(ApiResponse.success(environment)) : ResponseEntity.status(404).body(ApiResponse.fail(404, "Not Found"));
    }
    
    /**
     * 检查用户环境是否存在
     */
    @GetMapping("/{userId}/environment/exists")
    public ResponseEntity<ApiResponse<Map<String, Boolean>>> isUserEnvironmentExists(@PathVariable String userId) {
        boolean exists = userManagementService.isUserEnvironmentExists(userId);
        return ResponseEntity.ok(ApiResponse.success(Map.of("exists", exists)));
    }
    
    /**
     * 获取用户资源使用情况
     */
    @GetMapping("/{userId}/resources")
    public ResponseEntity<ApiResponse<UserResource>> getUserResourceUsage(@PathVariable String userId) {
        UserResource resource = userManagementService.getUserResourceUsage(userId);
        return ResponseEntity.ok(ApiResponse.success(resource));
    }
    
    /**
     * 设置用户资源限制
     */
    @PutMapping("/{userId}/resources/limits")
    public ResponseEntity<ApiResponse<Map<String, Object>>> setUserResourceLimits(
            @PathVariable String userId,
            @RequestBody UserResource resourceLimits) {
        boolean updated = userManagementService.setUserResourceLimits(userId, resourceLimits);
        Map<String, Object> response = Map.of(
            "updated", updated,
            "message", updated ? "Resource limits updated successfully" : "Failed to update resource limits"
        );
        return ResponseEntity.ok(updated ? ApiResponse.success(response) : ApiResponse.fail("Failed to update resource limits"));
    }
    
    /**
     * 重置用户密码
     */
    @PostMapping("/{userId}/password/reset")
    public ResponseEntity<ApiResponse<Map<String, Object>>> resetUserPassword(
            @PathVariable String userId,
            @RequestBody Map<String, String> request) {
        String newPassword = request.get("newPassword");
        boolean reset = userManagementService.resetUserPassword(userId, newPassword);
        Map<String, Object> response = Map.of(
            "reset", reset,
            "message", reset ? "Password reset successfully" : "Failed to reset password"
        );
        return ResponseEntity.ok(reset ? ApiResponse.success(response) : ApiResponse.fail("Failed to reset password"));
    }
    
    /**
     * 备份用户数据
     */
    @PostMapping("/{userId}/backup")
    public ResponseEntity<ApiResponse<Map<String, Object>>> backupUserData(@PathVariable String userId) {
        try {
            String backupPath = userManagementService.backupUserData(userId);
            Map<String, Object> response = Map.of(
                "backupPath", backupPath,
                "message", "Backup completed successfully"
            );
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail("Backup failed: " + e.getMessage()));
        }
    }
    
    /**
     * 恢复用户数据
     */
    @PostMapping("/{userId}/restore")
    public ResponseEntity<ApiResponse<Map<String, Object>>> restoreUserData(
            @PathVariable String userId,
            @RequestBody Map<String, String> request) {
        String backupPath = request.get("backupPath");
        boolean restored = userManagementService.restoreUserData(userId, backupPath);
        Map<String, Object> response = Map.of(
            "restored", restored,
            "message", restored ? "Data restored successfully" : "Failed to restore data"
        );
        return ResponseEntity.ok(restored ? ApiResponse.success(response) : ApiResponse.fail("Failed to restore data"));
    }
    
    /**
     * 获取系统资源使用统计
     */
    @GetMapping("/system/resources")
    public ResponseEntity<ApiResponse<UserResource>> getSystemResourceUsage() {
        UserResource systemResource = userManagementService.getSystemResourceUsage();
        return ResponseEntity.ok(ApiResponse.success(systemResource));
    }
    
    /**
     * 批量创建用户
     */
    @PostMapping("/batch")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createUsersBatch(@RequestBody List<User> users) {
        try {
            int successCount = 0;
            int failCount = 0;
            
            for (User user : users) {
                try {
                    userManagementService.createUser(user);
                    successCount++;
                } catch (Exception e) {
                    failCount++;
                }
            }
            
            Map<String, Object> response = Map.of(
                "successCount", successCount,
                "failCount", failCount,
                "message", String.format("Created %d users successfully, %d failed", successCount, failCount)
            );
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail("Batch creation failed: " + e.getMessage()));
        }
    }
    
    /**
     * 获取用户统计信息
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getUserStats() {
        List<User> allUsers = userManagementService.getAllUsers();
        
        long totalUsers = allUsers.size();
        long activeUsers = allUsers.stream().filter(u -> "ACTIVE".equals(u.getStatus())).count();
        long runningEnvironments = allUsers.stream()
                .map(u -> userManagementService.getUserEnvironmentStatus(u.getUserId()))
                .filter(env -> env != null && "RUNNING".equals(env.getStatus()))
                .count();
        
        Map<String, Object> stats = Map.of(
            "totalUsers", totalUsers,
            "activeUsers", activeUsers,
            "runningEnvironments", runningEnvironments,
            "stoppedEnvironments", totalUsers - runningEnvironments
        );
        
        return ResponseEntity.ok(ApiResponse.success(stats));
    }

    /**
     * 学生分页查询
     */
    @GetMapping("/students/page")
    public ResponseEntity<ApiResponse<PageResult<User>>> pageStudents(
            @RequestParam(defaultValue = "1") long pageNum,
            @RequestParam(defaultValue = "10") long pageSize,
            @RequestParam(required = false) String schoolName,
            @RequestParam(required = false) String collegeName,
            @RequestParam(required = false) String majorName,
            @RequestParam(required = false) String className,
            @RequestParam(required = false) String grade,
            @RequestParam(required = false) String studentNo,
            @RequestParam(required = false) String realName
    ) {
        Page<User> page = userManagementService.pageStudents(
                pageNum, pageSize, schoolName, collegeName, majorName, className, grade, studentNo, realName
        );
        return ResponseEntity.ok(ApiResponse.success(PageResult.from(page)));
    }

    /**
     * 列出可选的专业（去重）
     */
    @GetMapping("/students/majors")
    public ResponseEntity<ApiResponse<java.util.List<String>>> listMajors(
            @RequestParam(required = false) String like) {
        java.util.Set<String> set = new java.util.TreeSet<>();
        for (User u : userManagementService.getAllUsers()) {
            String m = u.getMajorName();
            if (m != null && !m.isBlank() && (like == null || m.contains(like))) set.add(m);
        }
        return ResponseEntity.ok(ApiResponse.success(new java.util.ArrayList<>(set)));
    }

    /**
     * 列出可选的班级（去重，可按专业过滤）
     */
    @GetMapping("/students/classes")
    public ResponseEntity<ApiResponse<java.util.List<String>>> listClasses(
            @RequestParam(required = false) String majorName,
            @RequestParam(required = false) String like) {
        java.util.Set<String> set = new java.util.TreeSet<>();
        for (User u : userManagementService.getAllUsers()) {
            if (majorName != null && !majorName.isBlank() && (u.getMajorName() == null || !u.getMajorName().contains(majorName))) continue;
            String c = u.getClassName();
            if (c != null && !c.isBlank() && (like == null || c.contains(like))) set.add(c);
        }
        return ResponseEntity.ok(ApiResponse.success(new java.util.ArrayList<>(set)));
    }
    
    /**
     * 修复用户容器权限
     */
    @PostMapping("/{userId}/fix-permissions")
    public ResponseEntity<ApiResponse<Map<String, Object>>> fixUserPermissions(@PathVariable String userId) {
        try {
            // 需要强制转换为实现类来访问 fixUserPermissions 方法
            if (userManagementService instanceof com.szgz.platform.service.impl.UserManagementServiceImpl) {
                com.szgz.platform.service.impl.UserManagementServiceImpl service = 
                    (com.szgz.platform.service.impl.UserManagementServiceImpl) userManagementService;
                boolean success = service.fixUserPermissions(userId);
                
                Map<String, Object> response = Map.of(
                    "success", success,
                    "message", success ? "Permissions fixed successfully" : "Failed to fix permissions"
                );
                
                return ResponseEntity.ok(success ? ApiResponse.success(response) : ApiResponse.fail("Failed to fix permissions"));
            } else {
                return ResponseEntity.internalServerError().body(ApiResponse.fail("Service implementation not available"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(ApiResponse.fail("Error: " + e.getMessage()));
        }
    }
    
    /**
     * 创建新用户（使用随机值）
     */
    @PostMapping("/random")
    public ResponseEntity<ApiResponse<User>> createRandomUser(@RequestParam(required = false, defaultValue = "student") String role) {
        try {
            User randomUser = userManagementService.createRandomUser(role);
            return ResponseEntity.ok(ApiResponse.success(randomUser));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /**
     * 批量创建随机用户
     */
    @PostMapping("/random/batch")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createRandomUsersBatch(
            @RequestParam(defaultValue = "1") int count,
            @RequestParam(required = false, defaultValue = "student") String role) {
        try {
            List<User> createdUsers = userManagementService.createRandomUsersBatch(count, role);
            Map<String, Object> response = Map.of(
                "message", "成功创建 " + count + " 个随机用户",
                "users", createdUsers
            );
            return ResponseEntity.ok(ApiResponse.success(response));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }
    
    /**
     * 解析环境类型参数
     * 支持的格式: "IDE", "JUPYTER", "IDE,JUPYTER"
     */
    private Set<UserEnvironment.EnvironmentType> parseEnvironmentTypes(String environmentTypes) {
        if (environmentTypes == null || environmentTypes.trim().isEmpty()) {
            throw new IllegalArgumentException("Environment types cannot be null or empty");
        }
        
        String[] types = environmentTypes.toUpperCase().split(",");
        Set<UserEnvironment.EnvironmentType> result = Arrays.stream(types)
                .map(String::trim)
                .map(type -> {
                    switch (type) {
                        case "IDE":
                            return UserEnvironment.EnvironmentType.IDE;
                        case "JUPYTER":
                            return UserEnvironment.EnvironmentType.JUPYTER;
                        case "JUPYTER_LIGHT":
                            return UserEnvironment.EnvironmentType.JUPYTER_LIGHT;
                        case "REDIS":
                            return UserEnvironment.EnvironmentType.REDIS;
                        case "MYSQL":
                            return UserEnvironment.EnvironmentType.MYSQL;
                        case "RABBITMQ":
                            return UserEnvironment.EnvironmentType.RABBITMQ;
                        case "ELASTICSEARCH":
                            return UserEnvironment.EnvironmentType.ELASTICSEARCH;
                        case "VIRTUAL_DESKTOP":
                            return UserEnvironment.EnvironmentType.VIRTUAL_DESKTOP;
                        case "FULL_STACK":
                            return UserEnvironment.EnvironmentType.IDE; // 暂时使用IDE替代FULL_STACK
                        default:
                            throw new IllegalArgumentException("Invalid environment type: " + type);
                    }
                })
                .collect(Collectors.toSet());
        
        // 如果同时包含IDE和JUPYTER，则保持原样
        // 不再转换为BOTH，因为BOTH枚举值已被移除
        
        return result;
    }

    /**
     * 获取所有共享IDE环境
     */
    @GetMapping("/shared/environment/ide")
    public ResponseEntity<ApiResponse<List<com.szgz.platform.model.SharedIDEEnvironment>>> getAllSharedIDEEnvironments() {
        try {
            List<com.szgz.platform.model.SharedIDEEnvironment> environments = userManagementService.getAllSharedIDEEnvironments();
            return ResponseEntity.ok(ApiResponse.success(environments));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(ApiResponse.fail("Failed to fetch environments"));
        }
    }

    /**
     * 根据组ID获取共享IDE环境
     */
    @GetMapping("/shared/environment/ide/{groupId}")
    public ResponseEntity<ApiResponse<com.szgz.platform.model.SharedIDEEnvironment>> getSharedIDEEnvironmentByGroupId(@PathVariable String groupId) {
        try {
            com.szgz.platform.model.SharedIDEEnvironment environment = userManagementService.getSharedIDEEnvironmentByGroupId(groupId);
            if (environment != null) {
                return ResponseEntity.ok(ApiResponse.success(environment));
            } else {
                return ResponseEntity.status(404).body(ApiResponse.fail(404, "Not Found"));
            }
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(ApiResponse.fail("Internal Server Error"));
        }
    }

    /**
     * 创建共享 JupyterHub 环境（老师选择多个学生创建账号）
     */
    @PostMapping("/shared/environment/jupyterhub")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createSharedJupyterHub(@RequestBody Map<String, Object> body) {
        String operatorRole = (String) body.getOrDefault("operatorRole", "");
        if (!isOperatorAllowed(operatorRole)) {
            return ResponseEntity.status(403).body(ApiResponse.fail(403, "Forbidden: only admin/teacher can create shared environment"));
        }

        String groupId = (String) body.get("groupId");
        Object ids = body.get("studentIds");
        if (groupId == null || ids == null) {
            return ResponseEntity.badRequest().body(ApiResponse.fail("groupId and studentIds are required"));
        }

        java.util.List<String> studentIds;
        if (ids instanceof java.util.List) {
            studentIds = ((java.util.List<?>) ids).stream().map(Object::toString).collect(java.util.stream.Collectors.toList());
        } else if (ids instanceof String) {
            studentIds = java.util.Arrays.stream(((String) ids).split(",")).map(String::trim).filter(s -> !s.isEmpty()).collect(java.util.stream.Collectors.toList());
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.fail("studentIds must be array or comma-separated string"));
        }

        try {
            Map<String, Object> result = userManagementService.createSharedJupyterHubEnvironment(groupId, studentIds);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /** 删除共享 JupyterHub 环境 */
    @DeleteMapping("/shared/environment/jupyterhub")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteSharedJupyterHub(@RequestParam String groupId,
                                                                      @RequestParam(required = false) String operatorRole) {
        if (!isOperatorAllowed(operatorRole)) {
            throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can delete shared environment");
        }
        try {
            Map<String, Object> result = userManagementService.deleteSharedJupyterHubEnvironment(groupId);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /** 通用：删除共享环境（同时尝试 IDE 与 JupyterHub） */
    @DeleteMapping("/shared/environment")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteSharedEnvironment(@RequestParam String groupId,
                                                                       @RequestParam(required = false) String operatorRole) {
        if (!isOperatorAllowed(operatorRole)) {
            throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can delete shared environment");
        }
        try {
            Map<String, Object> result = userManagementService.deleteSharedEnvironment(groupId);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /**
     * 创建共享 MySQL 环境（老师选择学生，统一容器内为每人创建账号与数据库）
     * 请求体示例：{"groupId":"class001", "studentIds":["stu01","stu02"], "operatorRole":"admin"}
     */
    @PostMapping("/shared/environment/mysql")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createSharedMySQL(@RequestBody Map<String, Object> body) {
        String operatorRole = (String) body.getOrDefault("operatorRole", "");
        if (!isOperatorAllowed(operatorRole)) {
            throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can create shared environment");
        }

        String groupId = (String) body.get("groupId");
        Object ids = body.get("studentIds");
        if (groupId == null || ids == null) {
            return ResponseEntity.badRequest().body(ApiResponse.fail("groupId and studentIds are required"));
        }

        java.util.List<String> studentIds;
        if (ids instanceof java.util.List) {
            studentIds = ((java.util.List<?>) ids).stream().map(Object::toString).collect(java.util.stream.Collectors.toList());
        } else if (ids instanceof String) {
            studentIds = java.util.Arrays.stream(((String) ids).split(",")).map(String::trim).filter(s -> !s.isEmpty()).collect(java.util.stream.Collectors.toList());
        } else {
            return ResponseEntity.badRequest().body(ApiResponse.fail("studentIds must be array or comma-separated string"));
        }

        try {
            Map<String, Object> result = userManagementService.createSharedMySQLEnvironment(groupId, studentIds);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /** 删除共享 MySQL 环境 */
    @DeleteMapping("/shared/environment/mysql")
    public ResponseEntity<ApiResponse<Map<String, Object>>> deleteSharedMySQL(@RequestParam String groupId,
                                                                 @RequestParam(required = false) String operatorRole) {
        if (!isOperatorAllowed(operatorRole)) {
            throw new com.szgz.platform.exception.BusinessException(403, "Forbidden: only admin/teacher can delete shared environment");
        }
        try {
            Map<String, Object> result = userManagementService.deleteSharedMySQLEnvironment(groupId);
            return ResponseEntity.ok(ApiResponse.success(result));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }
} 